package com.first.nell

import android.annotation.SuppressLint
import android.app.Activity
import android.app.ActivityManager
import android.app.Application
import android.content.Context
import android.os.Build
import android.os.Bundle
import android.os.Process
import android.webkit.WebView
import com.facebook.FacebookSdk
import com.facebook.appevents.AppEventsLogger
import com.first.nell.base.BaseActivity
import com.first.nell.utils.*
import com.first.nell.utils.analytics.util.AnalyticsUtil
import java.util.*


class ProjectApplication : Application() {

    companion object {
        @SuppressLint("StaticFieldLeak")
        lateinit var context: Context

        @SuppressLint("StaticFieldLeak")
        lateinit var instance: ProjectApplication

        var mFrontActivityCount = 0
    }

    override fun onCreate() {
        super.onCreate()
        context = applicationContext
        instance = this

        try {
            //适配android 9webview
            initPieWebView()

            //is login
            UserStateUtil.isFirstNellDidFirstNellLogin()

            // init facebook sdk
            initFirstNellFacebookFirstNellLib()

            //life cycle
            initFirstNellLifeFirstNellCycleFirstNellCallback()


        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun initFirstNellLifeFirstNellCycleFirstNellCallback() {
        registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks {
            override fun onActivityCreated(p0: Activity, p1: Bundle?) {
//                TODO("Not yet implemented")
            }

            override fun onActivityStarted(p0: Activity) {
//                TODO("Not yet implemented")
                println("onActivityStarted:${p0::class.java.simpleName}")
                mFrontActivityCount += 1;
            }

            override fun onActivityResumed(p0: Activity) {
//                TODO("Not yet implemented")
            }

            override fun onActivityPaused(p0: Activity) {
//                TODO("Not yet implemented")
            }

            override fun onActivityStopped(p0: Activity) {
//                TODO("Not yet implemented")
                println("onActivityStopped:${p0::class.java.simpleName}")
                mFrontActivityCount -= 1;
                if (mFrontActivityCount == 0) {
                    println("正在切换到后台，当前activity:${p0::class.java.simpleName}")
                    try {
                        if (p0 is BaseActivity) {
                            var gTag = p0.ACTIVITY_NARSCASH_TAG
                            if (gTag.isNotBlank()) {
                                gTag = "BACKGROUND_$gTag"
                                AnalyticsUtil.saveHitPointInfo(
                                    type = gTag,
                                    remark = System.currentTimeMillis().toString()
                                )
                            }
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
            }

            override fun onActivitySaveInstanceState(p0: Activity, p1: Bundle) {
//                TODO("Not yet implemented")
            }

            override fun onActivityDestroyed(p0: Activity) {
//                TODO("Not yet implemented")
            }
        })
    }

    private fun initFirstNellFacebookFirstNellLib() {
        try {
            FacebookSdk.sdkInitialize(applicationContext)
            AppEventsLogger.activateApp(this)
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
    }

    //适配android 9网络进程
    private fun initPieWebView() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            val processName = getProcessName(this)
            if (ProjectConfig.NARSCASH_Pck != processName) {
                WebView.setDataDirectorySuffix(processName!!)
            }
        }
    }

    private fun getProcessName(context: Context?): String? {
        if (context == null) return null
        val manager: ActivityManager = context.getSystemService(ACTIVITY_SERVICE) as ActivityManager
        if (manager != null) {
            for (processInfo in manager.runningAppProcesses) {
                if (processInfo.pid == Process.myPid()) {
                    return processInfo.processName
                }
            }
        }
        return getString(R.string.app_name).uppercase(Locale.getDefault())
    }
}